package com.binguo.thirdPay.hzShiMing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.thirdPay.MD5Util;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuritian
 * @Title: SrPayService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-06-22 09:47
 */
@Service
public class SrPayService {
    private static Logger logger = LoggerFactory.getLogger(SrPayService.class);

    //测试APPID
//    private static final String APPID = "90b6f1e3173740d99b40ae3296279b94";

    //正式APPID
    private static final String APPID = "d504cafa8f924bca866a25799b7182b7";

    private static final String CODE = "1111";

    //测试Key
//    private static final String KEY = "ZYCTZYCT";

    //正式Key
    private static final String KEY = "ZYCTWWZYCTWW";

    //测试URL
//    private static final String SRURL = "https://test.siruinet.com/sjzx/api";

    //正式URL
    private static final String SRURL = "https://citizenjoint.hzmz.gov.cn/api";

    //测试
//    private static final String PSHBH = "88888887";

    private static final String PSHMC = "智伴助餐服务";

    private static final String wsAppkey = "NW_HZSMKNW_HZSMK";

    private static final String wsAppid  = "95bc05063d3941fc8f27c68d9385ec11";

    private static final String wsCode = "1201";

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) {
        System.out.println(getSrPayPrice("00:D8:61:A7:79:3C","W15751860","徐燕","33900519770505514X","YUNPENG2019061717074582","15.0","4","88888887"));
        //System.out.println(getAddress("00:22:FB:20:D3:FE","GD190804000000231","YL2019061217"));
    }

    public static JSONObject getSrPayPrice(String pzdbh,
                                           String cardNo,
                                           String pxm,
                                           String psfzh,
                                           String orderNo,
                                           String pxfje,
                                           String pcardtype,
                                           String pshbh){
        if (pcardtype.equals("4")){
            pcardtype = "2";
        }else {
            pcardtype = "1";
        }
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        String result;
        Map<String, String> reqMap = createSrPayHead();
        reqMap.put("channel", "5");//智慧餐台
        reqMap.put("pshmc", PSHMC);
        reqMap.put("pshbh", pshbh);
        reqMap.put("pzdbh", pzdbh);
        reqMap.put("pposls", orderNo);
        reqMap.put("pfwlx", "2");
        reqMap.put("pfwxm", "");
        reqMap.put("pxph", cardNo);
        reqMap.put("pcardtype", pcardtype);
        reqMap.put("pxm", pxm);
        reqMap.put("psfzh", psfzh);
        reqMap.put("pxfje", pxfje);
        reqMap.put("ppsje", "0");
        result = getContent(reqMap);
        System.out.println(result);
        reqMap.put("sign", MD5Util.MD5Lower32(result+KEY));
        System.out.println(MD5Util.MD5Lower32(result+KEY));
        MultiValueMap map = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : reqMap.entrySet()) {
            map.add(entry.getKey(),entry.getValue());
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(SRURL+"/getOrder", requestBody, String.class);
        result = resp.getBody();
        JSONObject jsonResult = JSONObject.parseObject(result);
        if (jsonResult.getString("success").equals("true")){
            jsonResult = jsonResult.getJSONObject("data");
            logger.info("思锐data数据为:"+jsonResult.toJSONString());
            jsonResult = jsonResult.getJSONObject("body");
            logger.info("思锐body数据为:"+jsonResult.toJSONString());
            return jsonResult;
        }else {
            System.out.println(jsonResult.toJSONString());
            return null;
        }
    }

    public static JSONObject getAddress(String pzdbh,
                                        String orderNo,
                                        String pshbh){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        String result;
        Map<String, String> reqMap = createSrPayHead();
        reqMap.put("channel", "5");//智慧餐台
        reqMap.put("pshbh", pshbh);
        reqMap.put("pzdbh", pzdbh);
        reqMap.put("pywddh", orderNo);
        reqMap.put("plslx", "1");
        result = getContent(reqMap);
        System.out.println(result);
        reqMap.put("sign", MD5Util.MD5Lower32(result+KEY));
        result += "&sign="+MD5Util.MD5Lower32(result+KEY);
        MultiValueMap map = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : reqMap.entrySet()) {
            map.add(entry.getKey(),entry.getValue());
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(SRURL+"/getJyLsh", requestBody, String.class);
        result = resp.getBody();
        System.out.println(result);
        JSONObject jsonResult = JSONObject.parseObject(result);
        if (jsonResult.getString("success").equals("true")){
            jsonResult = jsonResult.getJSONObject("data");
            System.out.println(jsonResult.toJSONString());
            jsonResult = jsonResult.getJSONObject("body");
            System.out.println(jsonResult.toJSONString());
            return jsonResult;
        }else {
            System.out.println(jsonResult.toJSONString());
            return null;
        }
    }

    public JSONObject faceBinding(String certNo,
                                  String name,
                                  String cardNo,
                                  String cardKind,
                                  String image,
                                  String phoneNo){

        System.out.println("faceBinding");
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        String result;
        String reqSeq = getReqSeq();
        System.out.println(getReqSeq());
        System.out.println(Calendar.getInstance().getTime());
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("appid",APPID);
        reqMap.put("code",CODE);
        reqMap.put("timestamp",sdf.format(Calendar.getInstance().getTime()));
        reqMap.put("_input_charset","UTF-8");
        reqMap.put("reqSeq",reqSeq);
        reqMap.put("certNo",certNo);
        reqMap.put("name",name);
        reqMap.put("cardNo",cardNo);
        reqMap.put("cardKind",cardKind);
        reqMap.put("image",image);
        reqMap.put("phoneNo",phoneNo);
        System.out.println("reqMap=" + reqMap);
        result = getContent(reqMap);
        System.out.println("result=" + result);
        reqMap.put("sign", MD5Util.MD5Lower32(result+KEY));
        System.out.println("sign=" + reqMap.get("sign"));
        MultiValueMap map = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : reqMap.entrySet()) {
            map.add(entry.getKey(),entry.getValue());
        }


        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        System.out.println(SRURL);
        System.out.println(SRURL+"/buildBind");
        System.out.println(requestBody);
//        ResponseEntity<String> resp = restTemplate.postForEntity("https://test.siruinet.com/sjzx/api/buildBind", requestBody, String.class);
        ResponseEntity<String> resp = restTemplate.postForEntity(SRURL+"/buildBind", requestBody, String.class);
        result = resp.getBody();
        System.out.println(result);
        JSONObject jsonResult = JSONObject.parseObject(result);
        return jsonResult;
    }


    private static Map<String, String> createSrPayHead(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> reqMap = new HashMap<String, String>();
        reqMap.put("appid",APPID);
        reqMap.put("code",CODE);
        reqMap.put("timestamp",sdf.format(new Date()));
        reqMap.put("format","Json");
        reqMap.put("v","1.0");
        reqMap.put("_input_charset","UTF-8");
        return reqMap;
    }

    public static String getContent(Map params) {
        List keys = new ArrayList(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        boolean first = true;

        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);

            if ("sign".equals(key) || "_r".equals(key) || "_result_type".equals(key) || "_".equals(key)) {
                continue;
            }

            String value = String.valueOf(params.get(key));
            if (value == null || value.trim().length() == 0) {
                continue;
            }

            if (first) {
                prestr = prestr + key + "=" + value;
                first = false;
            } else {
                prestr = prestr + "&" + key + "=" + value;
            }
        }

        return prestr;
    }


    private static String getReqSeq(){
        return "YunPeng" + System.currentTimeMillis();
    }



}
